import React, { Component } from 'react'
import ETable from '../../components/ETable'
import Utils from '../../utils/Utils'
import Axios from '../../axios'
import menuConfig from '../../config/menuConfig'
import { Card, Button, Modal, Form, Input, Select, Tree, Transfer } from 'antd'
const FormItem = Form.Item
const Option = Select.Option
const TreeNode = Tree.TreeNode;

class Permission extends Component {
    state = {
        list: [],
        userInfo: {},
        menusInfo: {},
        isRoleVisible: false,
        isPermVisible: false,
        isUserVisible: false
    }
    params = {
        page: 1
    }
    componentDidMount() {
        this.requestList()
    }
    requestList = () => {
        Axios.ajax({
            url: '/role/list',
            data: {
                params: {
                    page: this.params.page
                }
            }
        }).then((res) => {
            if (res.code == '0') {
                this.setState({
                    list: res.result.item_list
                })
            }
        })
    }
    handleRole = () => {
        this.setState({
            isRoleVisible: true
        })
    }
    handleRoleSubmit = () => {
        let data = this.roleForm.props.form.getFieldsValue()
        Axios.ajax({
            url: '/role/create',
            data: data
        }).then((res) => {
            if (res.code == '0') {
                console.log(res)
                this.setState({
                    isRoleVisible: false
                })
                this.requestList()
                this.roleForm.props.form.resetFields()
            }
        })
    }
    handlePermission = () => {
        let data = this.state.selectedRows
        if (!data) {
            Modal.info({
                title: '温馨提示',
                content: '请选择一名用户'
            })
            return
        }
        this.setState({
            isPermVisible: true,
            userInfo: data,
            menusInfo: data[0].menus
        })
    }
    handlePermSubmit = () => {
        let data = this.PermForm.props.form.getFieldsValue();
        data.role_id = this.state.selectedRowKeys[0]
        data.menus = this.state.menusInfo
        Axios.ajax({
            url: '/permission/edit',
            data: {
                params: {
                    ...data
                }
            }
        }).then((res) => {
            if (res.code == '0') {
                this.setState({
                    isPermVisible: true
                })
            }
            this.requestList()
        })
    }
    handleUserAuth = () => {
        let data = this.state.selectedRows
        if (!data) {
            Modal.info({
                title: '温馨提示',
                content: "请选择一个角色"
            })
            return
        }

        this.setState({
            isUserVisible: true,
            detailInfo: data
        })
        this.getRoleUserList(data[0].id)
    }
    getRoleUserList = (id) => {
        Axios.ajax({
            url: '/role/user_list',
            data: {
                params: {
                    id
                }
            }
        }).then(res => {
            if (res.code == '0') {
                this.getAuthUserList(res.result)
            }
        })
    }
    //激活筛选目标
    getAuthUserList = (dataSoure) => {
        const mockData = [];
        const targetKeys = [];      //显示在右侧框数据的key集合
        if (dataSoure && dataSoure.length > 0) {
            for (let i = 0; i < dataSoure.length; i++) {
                const data = {
                    key: dataSoure[i].user_id,
                    title: dataSoure[i].user_name,
                    status: dataSoure[i].status
                }
                if (data.status == 1) {
                    targetKeys.push(data.key)
                }
                mockData.push(data)

            }
        }
        this.setState({
            mockData, targetKeys
        })
    }
    //提交
    handleUserSubmit=()=>{
        let data = {}
        data.user_ids = this.state.targetKeys;
        data.role_ids = this.state.selectedRows[0].id;
        Axios.ajax({
            url: '/role/user_role_edit',
            data: {
                params: {
                    ...data
                }
            }
        }).then(res => {
            console.log(res)
            if (res.code == '0') {
                this.setState({
                    isUserVisible: false
                })
                this.requestList()
            }
        })
    }
    render() {
        const columns = [
            {
                title: '角色ID',
                dataIndex: 'id',
                key: 'id',
            },
            {
                title: '角色名称',
                dataIndex: 'role_name',
                key: 'role_name',
            },
            {
                title: '创建时间',
                dataIndex: 'create_time',
                key: 'create_time',
            },
            {
                title: '使用状态',
                dataIndex: 'status',
                key: 'status',
                render: (status) => {
                    return status == '1' ? '启用' : '停用'
                }
            },
            {
                title: '授权时间',
                dataIndex: 'authorize_time',
                key: 'authorize_time',
            },
            {
                title: '授权人',
                dataIndex: 'authorize_user_name',
                key: 'authorize_user_name',
            }
        ]
        const data = [
            {
                key: '1',
                id: '1',
                role_name: '稻城',
                create_time: '1991-10-2',
                status: '1',
                authorize_time: '1993-11-03',
                authorize_user_name: '稻城'
            }
        ]
        return (

            <div>
                <Card>
                    <Button type="primary" onClick={this.handleRole}>创建角色</Button>
                    <Button type="primary" onClick={this.handlePermission}>设置权限</Button>
                    <Button type="primary" onClick={this.handleUserAuth}>用户授权</Button>
                </Card>
                <Card>
                    <ETable
                        updataSelectedItem={Utils.updataSelectedItem.bind(this)}
                        rowSelection
                        columns={columns}
                        dataSource={this.state.list}
                    >
                    </ETable>
                </Card>
                <Modal
                    title="创建角色"
                    visible={this.state.isRoleVisible}
                    onOk={this.handleRoleSubmit}
                    onCancel={() => {
                        this.setState({
                            isRoleVisible: false
                        })
                        this.roleForm.props.form.resetFields()
                    }}
                >
                    <RoleForm wrappedComponentRef={inst => this.roleForm = inst}></RoleForm>
                </Modal>
                <Modal
                    title="权限设置"
                    visible={this.state.isPermVisible}
                    onOk={this.handlePermSubmit}
                    onCancel={() => {
                        this.setState({
                            isPermVisible: false
                        })
                        this.PermForm.props.form.resetFields()
                    }}
                >
                    <PermForm
                        userInfo={this.state.userInfo}
                        menusInfo={this.state.menusInfo}
                        patchMenusInfo={(targetKeys) => {
                            this.setState({
                                menusInfo: targetKeys
                            })
                        }}
                        wrappedComponentRef={inst => this.PermForm = inst}
                    ></PermForm>
                </Modal>
                <Modal
                    title="用户授权"
                    visible={this.state.isUserVisible}
                    onOk={this.handleUserSubmit}
                    width={800}
                    onCancel={() => {
                        this.setState({
                            isUserVisible: false
                        })
                    }}
                >
                    <UserForm
                        detailInfo={this.state.detailInfo}
                        mockData={this.state.mockData}
                        targetKeys={this.state.targetKeys}
                        patchUserInfo={(targetKeys)=>{
                            this.setState({
                                targetKeys
                            })
                        }}
                        wrappedComponentRef={inst => this.UserForm = inst}
                    ></UserForm>
                </Modal>
            </div>
        )
    }
}
class RoleForm extends Component {
    render() {
        const { getFieldDecorator } = this.props.form
        const formItemLayout = {
            labelCol: {
                span: 5
            },
            wrapperCol: {
                span: 19
            },
        }
        return (
            <div>
                <Form layout="Horizontal">
                    <FormItem
                        {...formItemLayout}
                        label="角色名称："
                    >
                        {getFieldDecorator('role_name', {})(
                            <Input placeholder="请输入角色名称" />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="状态"
                    >
                        {getFieldDecorator('state', {
                            initialValue: '1'
                        })(
                            <Select>
                                <Option value='1'>开启</Option>
                                <Option value='0'>关闭</Option>
                            </Select>
                            )}
                    </FormItem>
                </Form>
            </div>
        )
    }
}
RoleForm = Form.create({})(RoleForm)
class PermForm extends Component {

    //渲染树事件
    renderTreeNodes = (data) => {
        return data.map((item, index) => {
            if (item.children) {
                return <TreeNode title={item.title} key={item.key}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            } else {
                return <TreeNode title={item.title} key={item.key}></TreeNode>
            }

        })
    }
    onCheck = (checkedKeys) => {
        this.props.patchMenusInfo(checkedKeys)
    }
    render() {
        const { getFieldDecorator } = this.props.form
        const formItemLayout = {
            labelCol: {
                span: 5
            },
            wrapperCol: {
                span: 19
            },
        }
        const userInfo = this.props.userInfo
        const menusInfo = this.props.menusInfo
        return (
            <Form layout="Horizontal">
                <FormItem
                    {...formItemLayout}
                    label="角色名称："
                >
                    {
                        getFieldDecorator('role_name', {
                            initialValue: userInfo[0].role_name
                        })(
                            <Input type="text" disabled />
                            )
                    }
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="状态："
                >
                    {
                        getFieldDecorator('state', {
                            initialValue: userInfo[0].status == '1' ? "启用" : "关闭"
                        })(
                            <Select>
                                <Option value="1">启用</Option>
                                <Option value="0">关闭</Option>
                            </Select>
                            )
                    }
                </FormItem>
                <Tree
                    checkable
                    onCheck={(checkedKeys) => {
                        this.onCheck(checkedKeys)
                    }}
                    checkedKeys={menusInfo}
                >
                    <TreeNode
                        title="平台权限"
                        key="platform_all"
                    >
                        {this.renderTreeNodes(menuConfig)}
                    </TreeNode>
                </Tree>
            </Form>
        )
    }
}
PermForm = Form.create({})(PermForm)
class UserForm extends Component {
    handleChange = (targetKeys) => {
        this.props.patchUserInfo(targetKeys)
    }
    render() {
        const { getFieldDecorator } = this.props.form
        const detailInfo = this.props.detailInfo
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 19 },
            },
        }
        return (
            <Form layout="horizontal">
                <FormItem
                    {...formItemLayout}
                    label="角色名称："
                >
                    {
                        getFieldDecorator('role_name', {
                            initialValue: detailInfo[0].role_name
                        })(
                            <Input type="text" disabled />
                            )
                    }
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="选择用户: "
                >
                    <Transfer
                        dataSource={this.props.mockData}
                        titles={['待选', '已选']}
                        listStyle={{ width: 200, height: 400 }}
                        showSearch
                        searchPlaceholder='输入用户名'
                        targetKeys={this.props.targetKeys}
                        onChange={this.handleChange}
                        render={item => item.title}
                    />
                </FormItem>
            </Form>
        )
    }
}
UserForm = Form.create({})(UserForm)
export default Permission